<?php

namespace App\Models\shop;

use Illuminate\Database\Eloquent\Model;
use Cache;

class goodscategory extends Model
{

    //白名单
    protected $fillable=['parent_id', 'name', 'thumb','type','url','is_show','sort_order','content'];

    //黑名单
//    protected $guarded = [];

    //关联自己
    public function children()
    {
        return $this->hasMany('App\Models\shop\goodscategory', 'parent_id', 'id');
    }

    //关联商品
    public function products()
    {
        return $this->hasMany('App\Models\shop\Product','category_id');
    }

    //加缓存写法
/*    static function get_categories()
    {
        $categories = Cache::rememberForever('xShop_category_categories', function () {
            return self::with(['children' => function ($query) {
                $query->orderBy('sort_order');
            }])->where('parent_id', 0)->orderBy('sort_order')->get();
        });

        return $categories;
    }*/

    //不加缓存写法
    static function get_categories()
    {

            return goodscategory::with(['children' => function ($query) {
                $query->orderBy('sort_order');
            }])->where('parent_id', 0)->orderBy('sort_order')->get();


        return $categories;
    }


    //筛选分类 屏蔽掉没有商品的分类
    static function filter_categories()
    {
        $categories=self::has('children.products')->with(['children'=>function($query){
            $query->has('products');
        }])->get();

        return $categories;
    }

}
